package me.shiqiang.im.common;

import com.corundumstudio.socketio.SocketIOClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Created by maliangxue on 2018/4/15.
 */
public class SocketClientMap {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private static SocketClientMap ourInstance = new SocketClientMap();

    public static SocketClientMap getInstance() {
        return ourInstance;
    }

    private ExecutorService executorService;

    private boolean stop = false;

    private SocketClientMap() {
        executorService = Executors.newSingleThreadExecutor();
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                while (!stop){
                    try {
                        logger.info("等待连接建立。。。");
                        Map<String, SocketIOClient> map = queue.take();
                        String key = map.keySet().iterator().next();
                        SocketIOClient socketIOClient = map.get(key);
                        Object serverId = socketIOClient.get("serverId");
                        ConnectionServer connectionServer = connectionServerMap.get(serverId);
                        if (connectionServer == null) {
                            connectionServer = new ConnectionServer(serverId.toString());
                            connectionServerMap.put(serverId.toString(), connectionServer);
                        }
                        if (key.equals("add")) {
                            connectionServer.addProcessor(socketIOClient);
                            logger.info("添加连接,serverId:{},machineId:{}",socketIOClient.get("serverId"),socketIOClient.get("machineId"));
                        } else {
                            connectionServer.removeProcessor(socketIOClient);
                            logger.info("删除连接,serverId:{},machineId:{}",socketIOClient.get("serverId"),socketIOClient.get("machineId"));
                        }
                    } catch (InterruptedException e) {
                        logger.error("error",e);
                        e.printStackTrace();
                    }

                }
            }
        });
    }

    private BlockingDeque<Map<String,SocketIOClient>> queue = new LinkedBlockingDeque<>();

    public Map<String,ConnectionServer> connectionServerMap = new HashMap<>();

    public void put(Map<String,SocketIOClient> eventMap){
        queue.add(eventMap);
    }
}
